# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import sqlite3

from bookstack.items import BookstackItem
from bookstack.spiders.book import BookSpider

class BookstackPipeline(object):
    def process_item(self, item, spider):
        print('300管道',item,spider.name)
        print(isinstance(item,BookstackItem),isinstance(spider,BookSpider)) # True
        return item


class SQlitePipeline(object):

    def open_spider(self,spider):
        """连接数据库"""
        print('引擎自动调用open_spider')
        self.conn = sqlite3.connect('bookstack.sqlite3')
        self.cur = self.conn.cursor()
        print(self.conn)

    def process_item(self, item,spider):
        """
        把item存储到数据库
        :param item:
        :return:
        """
        sql = "insert into book (title, href) VALUES (?,?)"
        self.cur.execute(sql,(item['text'],item['href']))
        self.conn.commit()
        return item

    def close_spider(self,spider):
        """关闭数据库"""
        print('引擎自动调用close_spider')
        self.cur.close()
        self.conn.close()